<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/7/2
 * Time: 22:26
 */

namespace common\models\Service;


use common\models\CommonFunction;
use common\models\DAO\DayAccrual;
use common\models\DAO\TeamBrokerage;
use common\models\DAO\TeamIntegral;
use common\models\DAO\User;
use common\models\DAO\UserIntegral;
use common\models\DAO\UserIntegralLog;
use common\models\DAO\UserWalletLog;

class TeamService {
    /*
     * 更新团队数据
     */
    public static function insert($param){
        $investUserID = $param['userID'];
        $money = $param['money'];
        $day = $param['day'];
        $userID = $param['recID'];
        $user = User::findOne($userID);
        $userInvestID = $param['userInvestID'];
        if(!$user){
            $user = User::findOne($investUserID);
            $user->recID = 0;
            $user->save();
            return true;
        }
        $investID = $param['investID'];
        $productID = $param['productID'];
        $setting = TeamSetting::getTeam($user['roleID']);
        $rate = $setting['rate'];
        $system_day = \Yii::$app->params['system_day'];
        $brokerage = intval($money * $rate * $day / $system_day / 10000);
        if($brokerage <= 0)
            return true;
        $now = time();
        $team_brokerage = new TeamBrokerage();
        $team_brokerage->investID = $investID;
        $team_brokerage->productID = $productID;
        $team_brokerage->userID = $userID;
        $team_brokerage->day = $day;
        $team_brokerage->investUserID = $investUserID;
        $team_brokerage->money = $money;
        $team_brokerage->brokerage = $brokerage;
        $team_brokerage->rate = $rate;
        $team_brokerage->createTime = $now;
        $team_brokerage->userInvestID = $userInvestID;
        $brokerage_result = $team_brokerage->save();

        if(!$brokerage_result)
            return false;
        //更新用户账号余额
        $date = date('Ymd');
        $dayAccrual = new DayAccrual();
        $dayAccrual->userID = $userID;
        $dayAccrual->date = $date;
        $dayAccrual->money = $brokerage;
        $dayAccrual->invest = $brokerage;
        $dayAccrual->createTime = $now;
        $dayAccrual->updateTime = $now;
        $dayAccrual->brokerageID = $team_brokerage->id;
        $accrual_result  = $dayAccrual->save();
        if(!$accrual_result)
            return false;
        //钱包明细
        $user_wallet = new UserWalletLog();
        $user_wallet->type = 1;
        $user_wallet->investID = $investID;
        $user_wallet->userInvestID = $userInvestID;
        $user_wallet->money = $brokerage;
        $user_wallet->createTime = $now;
        $user_wallet->userID = $userID;
        $user_wallet->road = 3;
        $user_wallet_result  = $user_wallet->save();

        if(!$user_wallet_result)
            return false;
        //c级推荐a获得积分逻辑
        if($user['recID'] != 0){
            $rec_user = User::findOne($user['recID']);
            if(!$rec_user){
                $user->recID = 0;
                $user->save();
                return true;
            }

            $scale = IntegralService::get(2, $day);
            $integral = intval($money / 100 / $scale );
            if($integral <= 0)
                return true;
            $team_integral = new TeamIntegral();
            $team_integral->investID = $investID;
            $team_integral->userID = $rec_user['id'];
            $team_integral->superiorsUserID = $user['id'];
            $team_integral->investUserID = $investUserID;
            $team_integral->userInvestID = $userInvestID;
            $team_integral->productID = $productID;
            $team_integral->money = $money;
            $team_integral->scale = $scale;
            $team_integral->createTime = $now;
            $team_integral->day = $day;
            $team_integral->integral = $integral;
            $team_integral_result = $team_integral->save();
            if(!$team_integral_result)
                return false;
            $user_integral = new UserIntegral();
            $user_integral->investID = $investID;
            $user_integral->userInvestID = $userInvestID;
            $user_integral->investUserID = $investUserID;
            $user_integral->userID = $rec_user['id'];
            $user_integral->createTime = $now;
            $user_integral->updateTime = $now;
            $user_integral->integral = $integral;
            $user_integral->usable = $integral;
            $user_integral->productID = $productID;
            $user_integral->type = 2;
            $user_integral_result = $user_integral->save();
            if(!$user_integral_result)
                return false;
            $user_integral_log = new UserIntegralLog();
            $user_integral_log->userID = $rec_user['id'];
            $user_integral_log->investID = $investID;
            $user_integral_log->userInvestID = $userInvestID;
            $user_integral_log->investUserID = $investUserID;
            $user_integral_log->createTime = $now;
            $user_integral_log->integral = $integral;
            $user_integral_log->productID = $productID;
            $user_integral_log->type = 1;
            $user_integral_log->road = 2;
            $user_integral_log->des = '好友['.CommonFunction::dealTel(CommonFunction::decrypt($user['phone'])).']邀请['.CommonFunction::dealTel($param['tel']).']投资';
            $user_integral_log_result = $user_integral_log->save();
            if(!$user_integral_log_result)
                return false;
        }
        return true;
    }

    /*
     * 分销积分
     */
    public static function integralList($userID, $page = 1, $limit = 10){
        if($page <= 0)
            $page = 1;
        if($limit <= 0)
            $limit = 10;
        $start = (intval($page) - 1) * $limit;
        $list = TeamIntegral::find()->where(['userID'=>$userID])->with('user')->asArray()->limit($limit)->offset($start)->orderBy('id desc')->all();
        $result = [];
        foreach($list as $v){
            $data['brokerage'] = intval($v['integral']);
            $data['time'] = date('Y-m-d H:i:s', $v['createTime']);
            $data['user'] = CommonFunction::dealTel(CommonFunction::decrypt($v['user']['phone']));
            $result[] = $data;
        }
        return $result;
    }
	
	/*
     * 分销积分条目总数
     */
    public static function integralListCount($userID)
	{
        return TeamIntegral::find()->where(['userID'=>$userID])->count();
    }
	

    /*
    * 积分金数
    */
    public static function integralTotal($userID){
        $integral = 0;
        $teamIntegral = TeamIntegral::find()->where(['userID'=>$userID])->sum('integral');
        if($teamIntegral)
            $integral = $teamIntegral;
        return $integral;
    }

    /*
   * 积分金数
   */
    public static function brokerageTotal($userID){
        $brokerage = 0;
        $teamBrokerage = TeamBrokerage::find()->where(['userID'=>$userID])->sum('brokerage');
        if($teamBrokerage)
            $brokerage = $teamBrokerage;
        return $brokerage;
    }

    /*
     * 积分初始化
     */
    public static function integralInit($userID){
        $result['total'] = intval(self::integralTotal($userID));
        $result['list'] = self::integralList($userID);
        return $result;
    }

    public static function count($user){
        $userID = $user['userID'];
        $role = $user['role'];
        $result['person'] = User::find()->where(['recID'=>$userID])->count();
        $result['integral'] = self::integralTotal($userID);
        $result['brokerage'] = CommonFunction::formatMoney(self::brokerageTotal($userID));
        $result['level'] = $role;
        $result['team_rate'] = TeamSetting::getTeam($role);
        return $result;
    }

    public static function myTeamBrokerage($userID){
        $myTeam = User::find()->where(['recID'=>$userID])->select('realName as name, id, phone, avatar, createTime')->asArray()->all();
        $ids = [];
        $list = [];
        $_brokerage = [];

        if($myTeam){
            foreach($myTeam as $vo){
                $ids[] = $vo['id'];
            }
            $brokerage = TeamBrokerage::find()->where(['investUserID'=>$ids])->groupBy('investUserID')->asArray()
                ->select('SUM(brokerage) as money, investUserID as id')->all();
            foreach($brokerage as $_v){
                $_brokerage[$_v['id']] = CommonFunction::formatMoney($_v['money']);

            }
            foreach($myTeam as $v){
                $_list['avatar'] = $v['avatar'];
                $_list['name'] = $v['name'];
                $_list['money'] = 0;
                $_list['tel'] = CommonFunction::decrypt($v['phone']);
                if(isset($_brokerage[$v['id']]))
                    $_list['money'] = $_brokerage[$v['id']];

                $_list['investUserID'] = $v['id'];
                $_list['createTime'] = date("Y-m-d",$v['createTime']);
                $list[] = $_list;
            }
        }
        return $list;
    }
    public static function myTeamIntegral($userID){
        $myTeam = User::find()->where(['recID'=>$userID])->select('realName as name, id, phone, avatar, createTime')->asArray()->all();
        $ids = [];
        $list = [];
        $_brokerage = [];

        if($myTeam){
            foreach($myTeam as $vo)
                $ids[] = $vo['id'];

            $brokerage = TeamIntegral::find()->where(['investUserID'=>$ids])->groupBy('investUserID')->asArray()
                ->select('SUM(integral) as integral, investUserID as id')->all();
            foreach($brokerage as $_v){
                $_brokerage[$_v['id']] = $_v['integral'];

            }
            foreach($myTeam as $v){
                $_list['integral'] = 0;
                $_list['avatar'] = $v['avatar'];
                $_list['name'] = $v['name'];
                $_list['tel'] = CommonFunction::decrypt($v['phone']);
                isset($_brokerage[$v['id']]) && $_list['integral'] = $_brokerage[$v['id']];
                $_list['investUserID'] = $v['id'];
                $_list['createTime'] = date("Y-m-d",$v['createTime']);
                $list[] = $_list;
            }
        }

        return $list;
    }
	
	//web我的团队初始化
	public static function initWeb($userID)
	{
		//积分总额
		$data['totalPoint']=self::integralTotal($userID)+0;
		//佣金总额
		$data['totalRage']=TeamBrokerage::find()->where(['userID'=>$userID])->sum('brokerage')+0;
		//团队总人数
		$connection = \Yii::$app->db; 
		$data['count']=$connection->createCommand('SELECT count(*) as total FROM `p2p_user` as a 
											where a.recID='.$userID)->queryAll()[0]['total'];
		return $data;
	}
}